package cnm.control;

import org.apache.log4j.Logger;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;

import cnm.exception.SimulatorException;
import cnm.parser.XmlCliCmdParser;
import cnm.pojo.CliBean;
import cnm.protocol.CliDeviceTelnet;
import cnm.validator.PatternFactory;
import cnm.validator.xpath.XPathValidatorFactory;
import cnm.validator.XmlSchemaValidator;

public class CentralControl {

    private static final Logger logger = Logger.getLogger(CentralControl.class);

    private static String COMMAND_FILE = System.getProperty("user.dir") + "/metadata/conf/cmd.txt";
    private static String RESULT_FILE = System.getProperty("user.dir") + "/metadata/result.txt";
    private static String TELNET_SERVER_ADDRESS = PropertyHolder.getDeviceIp();
    
    public static void main(String[] argv) throws InterruptedException {
        File cmdfile = new File(COMMAND_FILE);
        File resultfile = new File (RESULT_FILE);
        try {
            CliDeviceTelnet.commucate(TELNET_SERVER_ADDRESS, cmdfile, resultfile);
            
            XmlCliCmdParser parser = new XmlCliCmdParser(new FileInputStream(resultfile));
            List<CliBean> cliList = parser.getXmlCliCmdList();
            
            for (CliBean bean : cliList) {
                ByteArrayInputStream bain = new ByteArrayInputStream(bean.getResult().getBytes());
                String xsdfile = PatternFactory.getInstance().getPatternMap().get(bean.getCmd());
                logger.debug("Start validate response of {" + bean.getCmd() + "}...");
                
                if (xsdfile == null || xsdfile.trim().equals("")) {
                    logger.debug("The pattern of \"" + bean.getCmd() + "\" 's pattern is not defined");
                } else {
                    XmlSchemaValidator.validate(bain, xsdfile);
                    bain.reset();
                }
                
                String className = PatternFactory.getInstance().getClassMap().get(bean.getCmd());
                if (className == null || "".equals(className)) {
                    logger.debug("The class of \"" + bean.getCmd() + "\" 's class is not defined");
                } else {
                    XPathValidatorFactory.getInstance().createXPathValidator(className,bain).xpathCheck();
                }
                
                logger.debug("End validate response of {" + bean.getCmd() + "}...");
            }
            
        } catch (SimulatorException e) {
            e.printStackTrace();
            System.exit(1);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
         
        System.exit(0);
    }
    
}
